We define a harmounious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Note: The length of the input array will not exceed 20,000.
implSolution{pubfnfind_lhs(nums:Vec<i32>) -> i32{letmut max_len = 0;for i in0..nums.len(){if nums.contains(&(nums[i] + 1)){letmut len = 0;for j in0..nums.len(){if nums[j] == nums[i] || nums[j] == nums[i] + 1{ len += 1;}} max_len = max_len.max(len);}} max_len asi32}}
use std::collections::HashMap;implSolution{pubfnfind_lhs(nums:Vec<i32>) -> i32{letmut counter = HashMap::new();letmut max_len = 0;for num in nums {*counter.entry(num).or_insert(0) += 1;}for(num, cnt1)in counter.iter(){ifletSome(&cnt2) = counter.get(&(num + 1)){ max_len = max_len.max(cnt1 + cnt2);}} max_len }}
implSolution{pubfnfind_lhs(nums:Vec<i32>) -> i32{letmut nums = nums; nums.sort_unstable();letmut max_len = 0;letmut i = 0;letmut j = 1;while i < nums.len(){while j < nums.len() && nums[j] == nums[i]{ j += 1;}let k = j;if j < nums.len() && nums[j] == nums[i] + 1{while j < nums.len() && nums[j] == nums[i] + 1{ j += 1;} max_len = max_len.max(j - i);} i = k;} max_len asi32}}